//
//  CLStatusPictureView.swift
//  CLWeibo
//
//  Created by 陈亮 on 16/7/15.
//  Copyright © 2016年 陈亮. All rights reserved.
//

import UIKit
import SDWebImage
//重用标记
private let PictureViewCellId = "PictureViewCellId"
//cell之间的间距
private let itemMargin:CGFloat = 5
//每个collectionView item的宽度
private let itemWidth:CGFloat = (ScreenWidth - 2 * HomeCellMargin - 2 * itemMargin) / 3


class CLStatusPictureView: UICollectionView {

    //配图数据模型
    var picUrl:[CLStatusPictureInfo]? {
        didSet {
            let size = calsPictureViewSize(picUrl?.count ?? 0)
            //设置配图指定大小
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            //刷新数据
            self.reloadData()
        }
    }
    
    
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //垂直间距
        flowLayout.minimumLineSpacing = itemMargin
        //水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        //设置界面
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //添加控件 设置约束
    private func setUpUI() {
        //设置代理
        dataSource = self
        delegate = self
        //注册
        registerClass(CLStatusPictureViewCell.self, forCellWithReuseIdentifier: PictureViewCellId)
    }
    
    
    /**
    *  根据图片个数 来计算配图大小
    */
    private func calsPictureViewSize(count :Int) ->CGSize {
        //列数
        let cols = count > 3 ? 3 : count
        //行数
        let rows = (count - 1) / 3 + 1
        //计算当前配图的宽度
        let width = CGFloat(cols) * itemWidth + CGFloat(cols - 1) * itemMargin
        //配图的高度
        let height = CGFloat(rows) * itemWidth + CGFloat(rows - 1) * itemMargin
        //配图的尺寸
        let size = CGSize(width: width, height: height)
        return size
    }
}
//数据源方法
extension CLStatusPictureView:UICollectionViewDataSource ,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrl?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureViewCellId, forIndexPath: indexPath) as! CLStatusPictureViewCell
        cell.picInfo = picUrl![indexPath.item]
        return cell
    }
    //代理方法实现
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        /*
        SDPhotoBrowser *photoBrowser = [SDPhotoBrowser new];
        photoBrowser.delegate = self;
        photoBrowser.currentImageIndex = indexPath.item;
        photoBrowser.imageCount = self.modelsArray.count;
        photoBrowser.sourceImagesContainerView = self.collectionView;
        
        [photoBrowser show];
        
        */
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = picUrl!.count
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
    }
}

extension CLStatusPictureView:SDPhotoBrowserDelegate {
    
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        /*
        // 不建议用此种方式获取小图，这里只是为了简单实现展示而已
        SDCollectionViewDemoCell *cell = (SDCollectionViewDemoCell *)[self collectionView:self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
        
        return cell.imageView.image;
        */
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        let cell = self.cellForItemAtIndexPath(indexPath) as! CLStatusPictureViewCell
        return cell.imageView.image
    }
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        /*
        
        NSString *urlStr = [[self.modelsArray[index] thumbnail_pic] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
        return [NSURL URLWithString:urlStr];
        */
        let urlStr = picUrl![index].thumbnail_pic?.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: urlStr!)
    }
}
//自定义配图cell
class CLStatusPictureViewCell:UICollectionViewCell {
    
    //设置模型
    var picInfo:CLStatusPictureInfo? {
        didSet {
            if let imageUrl = picInfo?.thumbnail_pic {
                
                imageView.sd_setImageWithURL(NSURL(string: imageUrl), placeholderImage: UIImage(named: "timeline_image_placeholder"))
            }
        }
    }
    
    
    //懒加载控件
    private lazy var imageView:UIImageView = {
        
        let imgView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //确保图片原始比例
        imgView.contentMode = UIViewContentMode.ScaleAspectFill
        //裁剪多余的部分
        imgView.clipsToBounds = true
        return imgView
        
    }()
    //构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //设置约束
    private func setUpUI() {
        //先添加
        contentView.addSubview(imageView)
        //设置约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.size.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
    }
}
